// import EventItem from './page_item_events_item'
// import { isArray } from '@/utils/validate'
import { formatPageCpn } from './tools.js';

export default class PageItemCpns {
	cpns = [];
	_cpnTree = null;
	constructor(cpns) {
		cpns.map((cpn) => {
			const res = formatPageCpn(cpn, cpns);
			// console.log(res)
			if (res === null) {
				console.error('[Error][PageItemCpns]Cpn config invalid, cpn: ', cpn);
			} else {
				this.cpns.push(res);
			}
		});
		console.log('[Debug][PageItemCpns]Cpn tree: ', this.getTree());
	}

	getTree() {
		if (this._cpnTree !== null) {
			return this._cpnTree;
		}

		this._cpnTree = [];
		let cpnParent = null;
		const cpns = JSON.parse(JSON.stringify(this.cpns));
		while (cpns.length > 0) {
			const oldSize = cpns.length;
			for (let i = 0; i < oldSize; i++) {
				const cpn = cpns[0];
				cpns.shift();
				if (!cpn.PFormID) {
					// 没有父节点，则为顶层节点
					this._cpnTree.push(cpn);
					continue;
				}
				cpnParent = this.getTreeCpn(cpns, cpn.PFormID);
				if (cpnParent === null) {
					// 没找到父节点，放回原数组
					cpns.push(cpn);
					continue;
				}
				if (!cpnParent.children) {
					cpnParent.children = [];
				}
				cpnParent.children.push(cpn);
			}
			if (cpns.length === oldSize) {
				// 如果列表没发送变化，则没有可用数据了
				break;
			}
		}

		if (cpns.length > 0) {
			console.error('[Error][CustomPage][getCpnTree]Has invalid cpn config: ', cpns);
		}

		return this._cpnTree;
	}

	getTreeCpn(cpnTree, cpiID) {
		if (!cpnTree || !cpiID) {
			return null;
		}

		let ret = null;
		for (let i = 0; i < cpnTree.length; i++) {
			if (cpnTree[i].formId === cpiID) {
				return cpnTree[i];
			}
			if (!cpnTree[i].children) {
				continue;
			}
			for (let j = 0; j < cpnTree[i].children.length; j++) {
				ret = this.getTreeCpn([cpnTree[i].children[j]], cpiID);
				if (ret !== null) {
					return ret;
				}
			}
		}

		return null;
	}

	getCpn(cpn) {
		return this.cpns.find((c) => cpn === c.formId);
	}
}
